import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

// 确保这里没有 /api
const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8000';

const Login: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState('');
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const response = await fetch(`${API_BASE}/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          username: username,
          password: password,
        }).toString(),
      });

      const result = await response.json();

      if (result.code === 200) {
        localStorage.setItem('token', result.data.access_token);
        
        // 检查是否已选择书本
        try {
          const wordResponse = await fetch(`${API_BASE}/current-word`, {
            headers: {
              Authorization: `Bearer ${result.data.access_token}`,
            },
          });
          const wordResult = await wordResponse.json();
          
          if (wordResult.code === 404 && wordResult.msg === "请先选择要学习的书本") {
            navigate('/books');
          } else {
            navigate('/study');
          }
        } catch (error) {
          console.error('检查学习进度失败:', error);
          navigate('/books');
        }
      } else {
        // 登录失败时显示弹窗
        alert(result.msg || '登录失败，请检查用户名或密码。');
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      // 网络错误等异常情况显示弹窗
      alert('登录失败，请稍后再试。');
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2>用户登录</h2>
        <form onSubmit={handleLogin}>
          <div className="input-group">
            <label htmlFor="username">用户名:</label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </div>
          <div className="input-group">
            <label htmlFor="password">密码:</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <button type="submit" className="login-btn">登录</button>
        </form>
      </div>
    </div>
  );
};

export default Login; 